package com.tuanzi.loan.web.bean.family.push;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.jumai.server.common.util.ApiHost;
import com.starbaba.model.utils.HttpConnectionUtils;
import com.tuanzi.loan.business.constants.push.LoanPushMessageSendTaskStatus;
import com.tuanzi.loan.business.constants.push.PushMessageUserGroup;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.entity.push.LoanPushMessageSendTask;
import com.tuanzi.loan.business.service.common.CommProductIdService;
import com.tuanzi.loan.business.service.push.LoanPushMessageSendTaskService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.vo.view.family.push.SendPushMessageView;
import com.tuanzi.loan.web.configuration.JSFBean;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.server.loan_base.constant.weixin.LoanWechatCustomerMessageMsgType;
import com.tuanzi.server.loan_base.model.bean.push.PushMessage;
import com.tuanzi.server.loan_base.model.request.wechat.UploadPermanentImageRequest;
import com.tuanzi.server.loan_base.model.response.commom.Result;
import com.tuanzi.server.loan_base.model.response.commom.ResultUtils;
import com.tuanzi.server.loan_base.util.RedirectActionBuilder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.Date;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @Author: chenweijun
 * @Date: 2018/12/17 15:44
 * @Description:发送推送消息Bean
 */
@Data
@Debug
@Slf4j
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class SendPushMessageBean extends JSFInfoBean<SendPushMessageView>{

    @Autowired
    private LoanPushMessageSendTaskService loanPushMessageSendTaskService;

    @PostConstruct
    private void init(){

        String id = getParamFromRequest("id");
        if(StringUtils.isNotBlank(id)){
             LoanPushMessageSendTask sendTask = loanPushMessageSendTaskService.findOne(NumberUtils.toLong(id));
             $ = changeToSendPushMessageView(sendTask);
             changeStatusToView();
        }else{
            $ = new SendPushMessageView();
            changeStatusToAdd();
        }
    }

    /**
     * 上传图片到七牛
     * @param event
     */
    public void uploadImage(FileUploadEvent event) {
        String picUrl = this.uploadImg(event.getFile());
        $.setIcon(picUrl);
    }

    /**
     * 发送推送消息
     */
    public void onSend(){

        if(StringUtils.isBlank($.getTaskName())){
            addErrorMessage("请输入任务名称");
            return;
        }

        if($.getPushChannel() == null){
            addErrorMessage("请选择推送通道");
            return;
        }

        if($.getUserGroup() == null){
            addErrorMessage("请选择发送人群");
            return;
        }

        if($.getUserGroup() == PushMessageUserGroup.APP && CollectionUtils.isEmpty($.getProductIds())){
            addErrorMessage("请选择推送产品");
            return;
        }

        if($.getUserGroup() == PushMessageUserGroup.CALCULATE && CollectionUtils.isNotEmpty($.getProductIds())){
            addErrorMessage("基于计算的发送任务，不用选择产品。");
            return;
        }

        if(StringUtils.isBlank($.getIcon())){
            addErrorMessage("请上传Logo图");
            return;
        }

        if(StringUtils.isBlank($.getTitle())){
            addErrorMessage("请输入推送主标题");
            return;
        }

        if(StringUtils.isBlank($.getHtmlUrl())){
            addErrorMessage("请输入推送链接");
            return;
        }

        if($.getShowType() == null){
            addErrorMessage("请选择展示方式");
            return;
        }

        if($.getNotifyType() == null){
            addErrorMessage("请选择通知方式");
            return;
        }

        if($.getResponseType() == null){
            addErrorMessage("请选择响应方式");
            return;
        }

        LoanPushMessageSendTask sendTask = changeToSendTask($);
        loanPushMessageSendTaskService.saveOrUpdate(sendTask);
        addInfoMessage("操作成功,任务已加入发送队列");
    }


    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(PUSH_MESSAGE_SHOW_TYPE, PUSH_MESSAGE_NOTIFY_TYPE,
                PUSH_MESSAGE_RESPONSE_TYPE, PUSH_MESSAGE_CHANNEL, PUSH_MESSAGE_USER_GROUP);
    }


    /**
     * 转为发送任务
     * @param sendPushMessageView
     * @return
     */
    private LoanPushMessageSendTask changeToSendTask(SendPushMessageView sendPushMessageView){

        LoanPushMessageSendTask sendTask = new LoanPushMessageSendTask();
        sendTask.setTaskName(sendPushMessageView.getTaskName());
        sendTask.setPushChannel(sendPushMessageView.getPushChannel());
        sendTask.setStatus(LoanPushMessageSendTaskStatus.READY_SEND);
        sendTask.setSendTime(sendPushMessageView.getSendTime() != null ? sendPushMessageView.getSendTime() : new Date());
        sendTask.setUserGroup(sendPushMessageView.getUserGroup());
        if(CollectionUtils.isNotEmpty(sendPushMessageView.getProductIds())){
            sendTask.setProductId(StringUtils.join(sendPushMessageView.getProductIds(), ","));
        }

        //推送消息体
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTitle(sendPushMessageView.getTitle());
        pushMessage.setContent(sendPushMessageView.getContent());
        pushMessage.setIcon(sendPushMessageView.getIcon());
        pushMessage.setShowType(sendPushMessageView.getShowType());
        pushMessage.setNotifyType(sendPushMessageView.getNotifyType());
        pushMessage.setResponseType(sendPushMessageView.getResponseType());
        RedirectActionBuilder actionBuilder = new RedirectActionBuilder().htmlUrl(sendPushMessageView.getHtmlUrl());
        pushMessage.setResponseParams(actionBuilder.createMessageProtocol());

        sendTask.setMessage(new Gson().toJson(pushMessage));


        return sendTask;
    }


    /**
     * 转化为SendPushMessageView
     * @param sendTask
     * @return
     */
    private SendPushMessageView changeToSendPushMessageView(LoanPushMessageSendTask sendTask){

        PushMessage pushMessage = GsonUtils.toObject(sendTask.getMessage(), PushMessage.class);

        SendPushMessageView sendPushMessageView = new SendPushMessageView();

        sendPushMessageView.setTaskName(sendTask.getTaskName());
        sendPushMessageView.setSendTime(sendTask.getSendTime());
        sendPushMessageView.setPushChannel(sendTask.getPushChannel());
        sendPushMessageView.setUserGroup(sendTask.getUserGroup());
        sendPushMessageView.setProductIds(Lists.newArrayList(StringUtils.split(sendTask.getProductId(), ",")));
        sendPushMessageView.setIcon(pushMessage.getIcon());
        sendPushMessageView.setTitle(pushMessage.getTitle());
        sendPushMessageView.setContent(pushMessage.getContent());
        sendPushMessageView.setHtmlUrl(pushMessage.getResponseParams().getLaunchParams().htmlUrl);
        sendPushMessageView.setShowType(pushMessage.getShowType());
        sendPushMessageView.setNotifyType(pushMessage.getNotifyType());
        sendPushMessageView.setResponseType(pushMessage.getResponseType());

        return sendPushMessageView;

    }
}
